package com.bite.system.service.question.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bit.common.redis.service.RedisService;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.Constants;
import com.bite.common.core.enums.ResultCode;
import com.bite.common.security.exception.ServiceException;
import com.bite.system.domain.question.Question;
import com.bite.system.domain.question.dto.QuestionAddDTO;
import com.bite.system.domain.question.dto.QuestionEditDTO;
import com.bite.system.domain.question.dto.QuestionQueryDTO;
import com.bite.system.domain.question.vo.QuestionDetailVO;
import com.bite.system.domain.question.vo.QuestionHotVO;
import com.bite.system.domain.question.vo.QuestionVO;
import com.bite.system.elasticsearch.QuestionRepository;
import com.bite.system.manager.QuestionCacheManager;
import com.bite.system.mapper.question.QuestionMapper;
import com.bite.system.service.question.IQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionCacheManager questionCacheManager;

    @Autowired
    private RedisService redisService;

    @Override
    public List<QuestionVO> list(QuestionQueryDTO questionQueryDTO) {
        String questionIdsStr = questionQueryDTO.getExcludeQuestionIdsStr();
        if (StrUtil.isNotEmpty(questionIdsStr)) {
            String[] splitIdsStr = questionIdsStr.split(Constants.SPILT_SEM);
            Set<Long> splitIds = Arrays.stream(splitIdsStr).map(Long::parseLong).collect(Collectors.toSet());
            questionQueryDTO.setExcludeQuestionIdsSet(splitIds);
        }

//        PageHelper.startPage(questionQueryDTO.getPageNum(), questionQueryDTO.getPageSize());
        return questionMapper.list(questionQueryDTO);
    }

    @Override
    public int add(QuestionAddDTO questionAddDTO) {
        Question question = Question.creatByDTO(questionAddDTO);
        List<Question> questions = questionMapper.selectList(new LambdaQueryWrapper<>(Question.class)
                .select(Question::getTitle).eq(Question::getTitle, question.getTitle()));
        if (CollectionUtil.isNotEmpty(questions)) {
            throw new ServiceException(ResultCode.FAILED_ALREADY_EXISTS);
        }
        int insert = questionMapper.insert(question);
        questionCacheManager.addQuestion(question.getQuestionId());
        return saveES(question, insert);
    }

    @Override
    public QuestionDetailVO detail(Long questionId) {
        Question question = getQuestionById(questionId);
        return question.toDetailVO();
    }

    @Override
    public int edit(QuestionEditDTO questionEditDTO) {
        Question question = getQuestionById(questionEditDTO.getQuestionId());
        BeanUtil.copyProperties(questionEditDTO, question);
        int update = questionMapper.updateById(question);
        saveRedis(question);
        return saveES(question, update);
    }

    @Override
    public int delete(Long questionId) {
        getQuestionById(questionId);
        if (questionMapper.deleteById(questionId) == 0) {
            return 0;
        }
        questionRepository.deleteById(questionId);
        questionCacheManager.deleteQuestion(questionId);
        return 1;
    }


    private void saveRedis(Question question) {
        String key = getQuestionVOKey(question.getQuestionId());
        QuestionHotVO questionVO = new QuestionHotVO();
        BeanUtil.copyProperties(question, questionVO);
        redisService.setCacheObject(key, questionVO);
    }

    private String getQuestionVOKey(Long questionId) {
        return CacheConstants.QUESTION_HOT_DETAIL + questionId;
    }

    private Question getQuestionById(Long questionId) {
        Question question = questionMapper.selectById(questionId);
        if (question == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return question;
    }

    private Integer saveES(Question question, int flag) {
        if (flag == 0) {
            return 0;
        }
        // update ES data
        questionRepository.save(question.toES());
        return 1;
    }
}
